/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-01-17
 * Time: 16:25
 */
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //以穷举的方式 创建一棵二叉树出来
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    //求二叉树的高度
    public static int getHeight(TreeNode root) {
        //如果树为空
        if (root == null) {
            return 0;
        }
        //树不为空
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.max(leftHeight, rightHeight) + 1;
    }

    //求是否为平衡树O(n^2)
    public static boolean isBalanced1(TreeNode root) {
        if (root == null) {
            return true;
        }
        //求左子树和右子树的高度，然后计算高度差是否<=1,是则为平衡树否则不为平衡树
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if (Math.abs(leftH - rightH) <= 1 && isBalanced1(root.left) && isBalanced1(root.right)) {
            return true;
        }
        return false;
    }

    //O(n)
    public static boolean isBalanced2(TreeNode root) {
        if (root == null) {
            return true;
        }
        return getHeight1(root) >= 0;
    }

    public static int getHeight1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        //约定不是平衡树返回-1
        if (leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            return -1;
        }
    }
}